package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户注册
 */
@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf-8");
        int data = 0;  // 返回的结果标识 1=注册成功，非1标识注册失败
        String msg = "未知错误";
        // 1.从前端得到参数
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String password = req.getParameter("password");
        // 1.1 非空效验
        if (!StrUtil.isBlank(username) &&
                !StrUtil.isBlank(nickname) &&
                !StrUtil.isBlank(password)) {
            // 2.将数据保存到数据库
            // 2.1 得到连接
            Connection connection = DBUtils.getConnection();
            // 2.2 先判断登录名的唯一性
            String selSql = "select * from userinfo where username=?";
            // 2.3 得到执行器，执行执行器
            PreparedStatement statement = connection.prepareStatement(selSql);
            statement.setString(1, username);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                // 当前用户名已存在
                msg = "您输入的登录名已存在，请更换登录名再试！";
            } else {
                //  拼接sql，并获得执行
                String sql = "insert into userinfo(username,nickname,password) values(?,?,?)";
                statement = connection.prepareStatement(sql);
                //  给执行器填充属性，并执行
                statement.setString(1, username);
                statement.setString(2, nickname);
                statement.setString(3, SecureUtil.md5(password));
                data = statement.executeUpdate();
            }
            //  关闭资源
            DBUtils.close(resultSet, statement, connection);
        } else {
            msg = "非法参数！";
        }
        // 3.将数据库的结果返回给前端
        resp.getWriter().println(JSONUtil.toJsonStr(
                ResultUtils.toResult(200, data, msg)));
    }
}
